package com.xdf.advice;

import com.xdf.annotation.IgnoreResponseAdvice;
import com.xdf.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 拦截包 com.xdf 下响应结果，包装为统一返回对象
 * @author chanchaw
 * @create 2025-08-15 15:21
 */
@RestControllerAdvice(value="com.xdf")
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        if(methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)) return false;
        if(methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)) return false;
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 默认成功对象
        CommonResponse<Object> res = new CommonResponse<Object>(0,"");
        if(null == o) return res;
        // 如果原本是统一响应对象则强转后返回
        if(o instanceof CommonResponse) return (CommonResponse<Object>)o;

        res.setData(o);// 以上情况都不是则将 o 作为数据填充到统一响应对象并返回
        return res;
    }
}
